use crate::flow::parser::FlowPackage;
use serde_json::Value;
use snafu::ResultExt;
use std::path::Path;

pub async fn run_package(api_path: &Path, pkg: &FlowPackage) -> crate::Result<()> {
    let api = crate::api::Api::new(api_path, pkg.base_url.clone(), pkg.default_timeout_sec).await?;

    for (si, step) in pkg.steps.iter().enumerate() {
        println!(
            "==> Step {}: interface='{}', items={}",
            si + 1,
            step.interface,
            step.items.len()
        );

        for (ii, item) in step.items.iter().enumerate() {
            let res = match item {
                Value::Null => api.call(&step.interface, None).await,
                other => api.call(&step.interface, Some(other)).await,
            };

            if let Err(e) = res {
                return Err(e).whatever_context(format!(
                    "step {} (interface='{}') item {} failed",
                    si + 1,
                    step.interface,
                    ii + 1
                ))?;
            }
        }

        println!("    Step {} done.", si + 1);
    }

    println!("All steps done.");
    Ok(())
}
